﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Web;
using Twipler.App.Render;
using Twipler.App.Session;
using Twipler.Xtensions;

namespace Twipler.App
{
    public class HtmlRequest : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public bool IsReusable { get { return true; } }
     
        public void ProcessRequest(System.Web.HttpContext context)
        {
            if (App.Current.Visitor.IsAnonymous)
                context.Response.Redirect("default.aspx?lo");
            
            try
            {
                object[] dbg = Current.Log.EnterMethod("HtmlRequest: " + context.Request.Url.ToString());
                Current.SessionTrack.ViewingPage(context.Request.Url.ToString());

                PageProducer page = PageProducer.Get(context.Request.Url);
                if (page == null)
                {
                    context.Response.Write("<span style=\"color:#c04;\">Error</span><br/>" );
                    context.Response.Write("<br/><br/>Could not render the page.<a href=\"/\">Try again</a>.");
                }
                else
                {
                    if (context.Request.RequestType == "POST")
                        page.Postback(context.Request);

                    page.Render(context.Response);
                }
                Current.Log.ExitMethod(dbg);
            }
            catch (Exception ex)
            {
                Current.Log.Fatal("Exception: " + ex.Message);
                Twipler.WebApp.ExceptionReport.Report(ex);

                context.Response.Write("<span style=\"color:#c04;\">Exception!</span><br/>" + ex.Message);
                context.Response.Write("<br/><br/>Send message to @twipler to complain and maybe <a href=\"/\">Try again</a>.");
            }            
        }
    }
}